<template>
  <div>
    <el-form
      :model="questionForm"
      label-width="120px"
      :rules="questionFormRules"
      ref="questionFormRef"
    >
    <el-form-item label="分类">
      <el-cascader
      :options="treeData"
      @change="handleChange"
      class="cascader"
    />
    </el-form-item>
    <el-form-item label="题号" prop="num">
        <el-input v-model="questionForm.num"/>
      </el-form-item>
      <el-form-item label="单项多选" prop="type">
        <el-radio-group v-model="questionForm.type" class="ml-4">
          <el-radio label="1">单选</el-radio>
          <el-radio label="2">多选</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="题目内容" prop="examQuestion">
        <el-input v-model="questionForm.examQuestion" type="textarea" />
      </el-form-item>
      <el-form-item label="选项A" prop="option1">
        <el-input v-model="questionForm.option1" />
      </el-form-item>
      <el-form-item label="选项B" prop="option2">
        <el-input v-model="questionForm.option2" />
      </el-form-item>
      <el-form-item label="选项C" prop="option3">
        <el-input v-model="questionForm.option3" />
      </el-form-item>
      <el-form-item label="选项D" prop="option4">
        <el-input v-model="questionForm.option4" />
      </el-form-item>
      <el-form-item label="正确选项" prop="correct_id">
        <el-input v-model="questionForm.correct_id" />
      </el-form-item>
      <el-form-item label="解析" prop="analyse">
        <el-input v-model="questionForm.analyse" type="textarea" />
      </el-form-item>

      <el-form-item label="">
        <el-button type="primary" @click="submitForm()">添加题目</el-button>
        <el-button type="primary" @click="openExcel()">excel批量导入</el-button>
      </el-form-item>
    </el-form>
    <span>
    <input class="input-file" type="file" @change="exportData"
           accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
    <el-button type="warning" @click="btnClickExport">导入EXCEL</el-button>
  </span>
  </div>
</template>

<script setup>
import { ref, reactive,onMounted } from "vue";
import { ElMessage } from "element-plus";
import * as XLSX from 'xlsx'
import axios from 'axios'
const questionFormRef = ref();
let treeData = ref([])
let questionForm = ref({
  num:"",
  examQuestion: "",
  analyse: "",
  correct_id: [],
  option1: "",
  option2: "",
  option3: "",
  option4: "",
  type: "1",
  chapterId:'',
  seriesId:"",
  sectionId:"",
  teacherId:""
});
let excelData=ref([]);
onMounted(()=>{
  getTreeList()
})

const questionFormRules = reactive({
    num: [{ required: true, message: "请输入", trigger: "blur" }],
  examQuestion: [{ required: true, message: "请输入", trigger: "blur" }],
  analyse: [{ required: true, message: "请输入", trigger: "blur" }],
  correct_id: [{ required: true, message: "请输入", trigger: "blur" }],
  option1: [{ required: true, message: "请输入", trigger: "blur" }],
  option2: [{ required: true, message: "请输入", trigger: "blur" }],
  option3: [{ required: true, message: "请输入", trigger: "blur" }],
  option4: [{ required: true, message: "请输入", trigger: "blur" }],
  type: [{ required: true, message: "请输入", trigger: "blur" }],
});
const btnClick = ()  => {
      document.querySelector('.input-file').click()
    }
const handleChange = (value) => {
  questionForm.value.teacherId = value[0]
  questionForm.value.seriesId = value[1]
  questionForm.value.sectionId = value[2]
  questionForm.value.chapterId = value[3]
  console.log('value',value)
}
const getTreeList = async () => {
  let res = await axios.get("/adminapi/categoryTree/list");
  if (res.data.code == 200) {
    treeData.value = res.data.data;
    
    console.log("treeData", treeData.value);
  }
};
const exportData = (event) => {
      if (!event.currentTarget.files.length) {
        return
      }
      const that = this
      // 拿取文件对象
      var f = event.currentTarget.files[0]
      // 用FileReader来读取
      var reader = new FileReader()
      // 重写FileReader上的readAsBinaryString方法
      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = ''
        var wb // 读取完成的数据
        var outdata // 你需要的数据
        var reader = new FileReader()
        reader.onload = function (e) {
          // 读取成Uint8Array，再转换为Unicode编码（Unicode占两个字节）
          var bytes = new Uint8Array(reader.result)
          var length = bytes.byteLength
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i])
          }
          // 接下来就是xlsx了，具体可看api
          wb = XLSX.read(binary, {
            type: 'binary'
          })
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
          // 自定义方法向父组件传递数据
          console.log('outdata = ', outdata)
          excelData.value = outdata
         
          
        }
        reader.readAsArrayBuffer(f)
      }
      reader.readAsBinaryString(f)
    }
const btnClickExport = async () => {
  let params = {
            chapterId:questionForm.value.chapterId,
            seriesId:questionForm.value.seriesId,
            sectionId:questionForm.value.sectionId,
            teacherId:questionForm.value.teacherId,
            questionList:excelData.value
          }
          console.log('params',params)
        let res = await  axios.post('/adminapi/question/addList',params)
        if(res.data.code == 200) {
          ElMessage.success('添加成功')
        }else {
          ElMessage.error('添加失败')
        }
        excelData.value = []
}
const submitForm = () => {
    questionFormRef.value.validate(async(valid) => {
        if(valid) {
            console.log('questionForm',questionForm.value)
            let res = axios.post('/adminapi/question/add',questionForm.value)
            if(res.data.code == 200) {
              ElMessage.success('添加成功')
            }else{
              ElMessage.error('添加失败')
            }
        }
    })
}
</script>

<style>
.cascader {
  width: 100%;
}
</style>